using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour 
{
	public float jumpForce = 500;
	public float holdJumpForce = 10;
	public float notHoldJumpForce = -20;
	public float moveSpeed = 200;
	
	public bool isAlive = true;
	public bool firstGen = false;
	
	public bool doubleJumpEnabled = false;
	private bool doubleJump = true;
	
	private bool touchingPlatform = true;
	
	private int loadedLevel;
	public int currentLevel;
	
	// Use this for initialization
	void Start ()
	{
		//Adds values onto static values if wasn't first generation
		if(!firstGen)
		{
			jumpForce += PlayerData.jumpForce;
			holdJumpForce += PlayerData.holdJumpForce;
			notHoldJumpForce += PlayerData.notHoldJumpForce;
			moveSpeed += PlayerData.moveSpeed;
		}
	}
	
	// Update is called once per frame
	void Update () 
	{ 
		if(isAlive)
		{
			//gameObject.rigidbody.AddForce(new Vector3(moveSpeed, 0, 0));
			transform.Translate(moveSpeed * Time.deltaTime, 0f, 0f);
		
			if(Input.GetButtonDown("Jump"))
			{
				if(touchingPlatform)
				{ 
					gameObject.rigidbody.AddForce(new Vector3(0, jumpForce, 0));
				}
				else if(doubleJumpEnabled && doubleJump)
				{
					doubleJump = false;
					gameObject.rigidbody.AddForce(new Vector3(0, jumpForce, 0));
				}
			}
			
			if(!touchingPlatform)
			{
				if (Input.GetButton ("Jump"))
				{
					gameObject.rigidbody.AddForce(new Vector3(0, holdJumpForce, 0));
				}
				else
				{
					if(gameObject.rigidbody.velocity.y<0.2f)
					{
						gameObject.rigidbody.AddForce(new Vector3(0, notHoldJumpForce, 0));
					}
				}
			}
			
		}
		
		if(Input.GetButtonDown("Start"))
		{
			if(gameObject.tag=="Player1")
			{
				Debug.Log("Start pushed");
				isAlive = true;
				transform.position= new Vector3(0, 0, transform.position.z);
				
				//Resetting sound effects
				GameObject[] gameObj = GameObject.FindGameObjectsWithTag("Obstacle");
			
				for(int i =0; i<gameObj.Length; i++)
				{
					if(gameObj[i].GetComponentInChildren<DeathTrigger>()!=null)
					{
						gameObj[i].GetComponentInChildren<DeathTrigger>().soundTrigger = false;
					}
				}
				
				
				PlayerData.levelScore = 0;
				PlayerData.scoreMultiplier = 1;
				
				//loadedLevel = Application.loadedLevel;
				Debug.Log("Loaded level is: " + currentLevel);
			
				Application.LoadLevel(Application.loadedLevel);
			}
		}
	}
	
	void OnCollisionEnter () 
	{
		touchingPlatform = true;
		doubleJump = true;
	}

	void OnCollisionExit () 
	{
		touchingPlatform = false;
	}
}
